<template>
  <div>
    <el-dialog :title="!id?'新增优惠券':disabled?'查看优惠券':'编辑优惠券'" top="5vh" center :visible.sync="dialogVisible" width="60%" :before-close="handleClose" @open="openDialog">
      <el-form ref="form" :disabled="disabled" :model="form" v-loading="formLoading" :rules="rules" label-width="150px">
        <el-form-item label="用户类型：" prop="trait">
          <div>
            <el-radio v-model="form.trait" :label="0">普通券</el-radio>
            <span class="c_red">（指全部用户可用的优惠券，发布后用户在规定时间内领取）</span>
          </div>
          <div v-if="form.mode===0">
            <el-radio v-model="form.trait" :label="1">新人券</el-radio>
            <span class="c_red">（指新用户可用的优惠券，注册完成之后，系统自动将所有新人券发放给用户）</span>
          </div>
        </el-form-item>
        <!-- <el-form-item label="优惠类型：" prop="type">
          <el-checkbox v-model="form.type" :false-label="-1" :true-label="0">满减券</el-checkbox>
        </el-form-item> -->
        <el-form-item label="优惠券名称：" prop="name">
          <el-input v-model="form.name" maxlength="20" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="发放总量：" prop="issue_number">
          <el-input-number size="small" :precision="0" v-model="form.issue_number" controls-position="right" :min="-1" :max="10000000"></el-input-number> 张
          <span class="c_red">（-1代表不限制总量）</span>
        </el-form-item>
        <el-form-item label="使用门槛：" prop="has_threshold">
          <div>
            <el-radio v-model="form.has_threshold" :label="true">
              订单满 <el-input-number size="small" :precision="2" :step="0.01" v-model="form.threshold" controls-position="right" :min="0"></el-input-number> 元
            </el-radio>
          </div>
          <div>
            <el-radio v-model="form.has_threshold" :label="false">无门槛</el-radio>
          </div>
        </el-form-item>
        <el-form-item label="使用描述：" prop="content">
          <el-input v-model="form.content" maxlength="100" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="优惠金额：" prop="face_value">
          减免 <el-input-number size="small" :step="0.01" :precision="2" v-model="form.face_value" controls-position="right" :min="0"></el-input-number> 元
        </el-form-item>
        <el-form-item label="有效期：" prop="expired_day">
          领取后生效 <el-input-number size="small" :precision="0" v-model="form.expired_day" controls-position="right" :min="0"></el-input-number> 天
        </el-form-item>
        <el-form-item label="每人限领张数：" prop="receive_limit">
          <el-input-number size="small" v-model="form.receive_limit" :precision="0" controls-position="right" :min="-1"></el-input-number> 次
          <span class="c_red">（新人券建议限领1次，-1代表不限制）</span>
        </el-form-item>
        <el-form-item label="其他活动是否参与：">
          <el-checkbox-group v-model="activity_arr" @change="activityArrChange">
            <el-checkbox :label="0">拼团</el-checkbox>
            <el-checkbox :label="1">秒杀</el-checkbox>
            <!-- <el-checkbox :label="2">首单优惠</el-checkbox> -->
          </el-checkbox-group>
          <div class="c_red">（不勾选则默认为其他活动不可参与此优惠券活动，勾选后则支持叠加使用）</div>
        </el-form-item>
        <el-form-item label="领取时间：" prop="timeArr">
          <el-date-picker v-model="form.timeArr" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="使用范围：" prop="modeType">
          <div class="flex">
            <!-- <el-select v-model="form.mode" placeholder="用户类型" clearable>
              <el-option label="平台券" :value="0"></el-option>
              <el-option label="店铺券" :value="1"></el-option>
            </el-select> -->
            <div v-if="form.mode===0" class="ml20">
              <el-radio v-model="form.modeType" :label="1">全部店铺</el-radio>
              <el-radio v-model="form.modeType" :label="2">指定店铺不可用</el-radio>
              <el-radio v-model="form.modeType" :label="3">指定店铺可用</el-radio>
            </div>
            <div v-if="form.mode===1" class="ml20">
              <el-radio v-model="form.modeType" :label="1">全部商品</el-radio>
              <el-radio v-model="form.modeType" :label="2">指定商品不可用</el-radio>
              <el-radio v-model="form.modeType" :label="3">指定商品可用</el-radio>
            </div>
          </div>
        </el-form-item>
        <div class="tableBox" v-if="(form.modeType==2||form.modeType==3)&&form.mode===0">
          <div class="flex_bet">
            <h4>{{mode===0?'选择店铺':'选择商品'}}</h4>
            <div>
              <el-button type="primary" size="small" @click="innerVisible=true">选择店铺</el-button>
            </div>
          </div>
          <el-table :data="selShops" border style="width: 100%;">
            <el-table-column align="center" type="index" label="序号" width="80"> </el-table-column>
            <el-table-column prop="company_name" header-align="center" align="center" label="店铺名称">
            </el-table-column>
            <el-table-column prop="loser" header-align="center" align="center" label="联系人">
            </el-table-column>
            <el-table-column prop="mobile" header-align="center" align="center" label="联系电话">
            </el-table-column>
            <el-table-column prop="province" header-align="center" align="center" label="店铺地址">
            </el-table-column>
            <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
              <template slot-scope="{row,$index}">
                <el-button type="text" size="small" @click="delSelShop(row,$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="tableBox" v-if="(form.modeType==2||form.modeType==3)&&form.mode===1">
          <div class="flex_bet">
            <h4>{{mode===0?'选择店铺':'选择商品'}}</h4>
            <div>
              <el-button type="primary" size="small" @click="innerVisible=true">{{mode===0?'选择店铺':'选择商品'}}</el-button>
            </div>
          </div>
          <el-table :data="selShops" border style="width: 100%;">
            <el-table-column align="center" type="index" label="序号" width="80"> </el-table-column>
            <el-table-column prop="company_name" header-align="center" align="center" label="商品图片">
              <template slot-scope="{row}">
                <el-popover placement="left" title trigger="hover">
                  <img :src="row.cover" style="height: 200px;margin-right: 10px;">
                  <img slot="reference" @click="$openImg(row.cover)" :src="row.cover" style="height: 50px;width: 50px;margin-right: 10px;">
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column prop="title" header-align="center" align="center" label="商品名称">
            </el-table-column>
            <el-table-column prop="mobile" header-align="center" align="center" label="商品价格（元）">
              <template slot-scope="scope">
                <span>{{scope.row.min_sale_price==scope.row.max_sale_price?scope.row.min_sale_price:scope.row.min_sale_price+'~'+scope.row.max_sale_price}}</span>
              </template>
            </el-table-column>
            <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
              <template slot-scope="{row,$index}">
                <el-button type="text" size="small" @click="delSelShop(row,$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submit" v-if="!disabled" :loading="btnLoading">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 选择店铺弹窗 选择商品弹窗-->
    <el-dialog width="60%" :title="form.mode===0?'选择店铺':'选择商品'" :visible.sync="innerVisible" append-to-body closed="closeShop" @open="openShopsDialog">
      <el-form :inline="true" :model="shopPamars" v-if="innerVisible&&form.mode===0">
        <el-form-item label="店铺名称">
          <el-input v-model="shopPamars.title" :maxlength="20" placeholder="店铺名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="getShopList()">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-table ref="shopTab" v-if="innerVisible&&form.mode===0" :data="shopList" border v-loading="shopTableLoading" style="width: 100%;" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" :selectable="selected">
        </el-table-column>
        <el-table-column align="center" type="index" label="序号" width="80"> </el-table-column>
        <el-table-column prop="company_name" header-align="center" align="center" label="店铺名称">
        </el-table-column>
        <el-table-column prop="loser" header-align="center" align="center" label="联系人">
        </el-table-column>
        <el-table-column prop="mobile" header-align="center" align="center" label="联系电话">
        </el-table-column>
        <el-table-column prop="province" header-align="center" align="center" label="店铺地址">
        </el-table-column>
      </el-table>

      <el-form :inline="true" :model="shopPamars" v-if="innerVisible&&form.mode===1">
        <el-form-item label="商品名称">
          <el-input v-model="shopPamars.title" :maxlength="20" placeholder="商品名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="getGoodsList()">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-table ref="shopTab" v-if="innerVisible&&form.mode===1" :data="shopList" border v-loading="shopTableLoading" style="width: 100%;" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" :selectable="selected">
        </el-table-column>
        <el-table-column align="center" type="index" label="序号" width="80"> </el-table-column>
        <el-table-column prop="company_name" header-align="center" align="center" label="商品图片">
          <template slot-scope="{row}">
            <el-popover placement="left" title trigger="hover">
              <img :src="row.cover" style="height: 200px;margin-right: 10px;">
              <img slot="reference" @click="$openImg(row.cover)" :src="row.cover" style="height: 50px;width: 50px;margin-right: 10px;">
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="title" header-align="center" align="center" label="商品名称">
        </el-table-column>
        <el-table-column prop="price" header-align="center" align="center" label="商品价格（元）">
          <template slot-scope="scope">
            <span>{{scope.row.min_sale_price==scope.row.max_sale_price?scope.row.min_sale_price:scope.row.min_sale_price+'~'+scope.row.max_sale_price}}</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="pageBox">
        <el-pagination @size-change="sizeChangeShop" @current-change="currentChangeShop" :current-page="shopPamars.page" :page-sizes="[10, 20, 50, 100]" :page-size="shopPamars.limit" :total="shopTotal" layout="total, sizes, prev, pager, next, jumper"></el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeShop">取 消</el-button>
        <el-button type="primary" v-if="!disabled" @click="confirmShops">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import couponApi from '@/api/couponApi.js'
import serviceApione from '@/api/serviceApione.js'
import seviceApi from '@/api/serviceApi.js'
export default {
  data () {
    return {
      formLoading: false,
      form: {
        type: 0,//优惠券类型只能是满减券
        mode: this.mode,//固定是平台券
        trait: 1,
        adapt_activity_data: [
          { code: 'GROUPBUY', on: false },
          { code: 'SECKILL', on: false },
          { code: 'FIRSTORDER', on: false }
        ]
      },
      rules: {
        name: [
          { required: true, message: '请输入优惠券名称', trigger: 'change' }
        ],
        issue_number: [
          { required: true, message: '请输入发放总量', trigger: 'change' }
        ],
        has_threshold: [
          { required: true, message: '请选择使用门槛', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入使用描述', trigger: 'change' }
        ],
        face_value: [
          { required: true, message: '请输入优惠金额', trigger: 'change' }
        ],
        expired_day: [
          { required: true, message: '请输入有效期', trigger: 'change' }
        ],
        receive_limit: [
          { required: true, message: '请输入每人限领张数', trigger: 'change' }
        ],
        timeArr: [
          { required: true, message: '请选择领取时间', trigger: 'change' }
        ],
        modeType: [
          { required: true, message: '请选择使用范围', trigger: 'change' }
        ]
      },
      activity_arr: [],
      btnLoading: false,
      innerVisible: false,//选择店铺弹窗开关
      shopPamars: {
        page: 1,
        limit: 10
      },
      shopList: [],//店铺列表
      shopTotal: 0,//店铺总数
      shopTableLoading: false,
      temShops: [],//临时选择店铺对象数组
      selShops: [],//选择店铺对象数组
    }
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    id: {
      type: Number | String
    },
    mode: {
      type: Number,
      default: 0
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    dialogVisible: {
      get () {
        return this.show
      },
      set (val) {
        this.$emit("update:show", val)
      }
    }
  },
  methods: {
    handleClose () {
      this.$refs.form.resetFields();
      this.form = {
        type: 0,//优惠券类型只能是满减券
        mode: this.mode,//固定是平台券
        trait: 1,
        adapt_activity_data: [
          { code: 'GROUPBUY', on: false },
          { code: 'SECKILL', on: false },
          { code: 'FIRSTORDER', on: false }
        ]
      };
      this.activity_arr = [];
      this.dialogVisible = false
    },
    // 其他活动是否参与
    activityArrChange (e) {
      this.form.adapt_activity_data = [
        { code: 'GROUPBUY', on: false },
        { code: 'SECKILL', on: false },
        { code: 'FIRSTORDER', on: false }
      ];
      e.forEach(v => {
        this.form.adapt_activity_data[v].on = true
      });
    },
    // 开启外层弹窗时
    openDialog () {
      this.selShops = [];
      if (this.id) {
        this.getDetails()
      }
    },
    // 提交
    submit () {
      console.log(this.form)
      if (this.form.has_threshold && !this.form.threshold) {
        this.$message.error("请输入门槛金额！")
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 重新定义  领取时间字段
          this.form.start_time = this.form.timeArr[0];
          this.form.end_time = this.form.timeArr[1];
          // 重新定义  使用范围字段
          if (this.form.modeType == 1) {
            this.form.universal = true;
            this.form.adapt_or_no = false;
          } else if (this.form.modeType == 2) {
            this.form.universal = false;
            this.form.adapt_or_no = false;
          } else if (this.form.modeType == 3) {
            this.form.universal = false;
            this.form.adapt_or_no = true;
          }
          // 获取选择的部门id
          if (!this.form.universal) {
            this.form.adapt_shop_ids = this.selShops.map(v => {
              return v.id
            })
            if (!this.form.adapt_shop_ids || this.form.adapt_shop_ids.length <= 0) {
              this.$message.error('选择的店铺个数不能少于1！')
              return
            }
          }
          if (this.id) {
            this.update()
          } else {
            this.add()
          }
        }
      })
    },
    // 新增
    add () {
      this.btnLoading = true;
      couponApi.couponAdd(this.form).then(res => {
        this.btnLoading = false;
        if (res && res.data.code == 200) {
          this.$message.success('新增成功！');
          this.handleClose();
          this.$emit('change')
        }
      })
    },

    // 修改
    update () {
      this.btnLoading = true;
      couponApi.couponUpdate(this.form).then(res => {
        this.btnLoading = false;
        if (res && res.data.code == 200) {
          this.$message.success('修改成功！');
          this.handleClose();
          this.$emit('change')
        }
      })
    },
    // 每页数
    sizeChangeShop (val) {
      this.shopPamars.limit = val
      if (this.mode === 0) {
        this.getShopList();
      } else {
        this.getGoodsList()
      }
    },
    // 当前页
    currentChangeShop (val) {
      this.shopPamars.page = val
      if (this.mode === 0) {
        this.getShopList();
      } else {
        this.getGoodsList()
      }
    },
    // 获取店铺列表
    getShopList () {
      this.shopTableLoading = true;
      seviceApi.getShopList(this.shopPamars).then(res => {
        this.shopTableLoading = false;
        if (res && res.data.code == 200) {
          this.shopList = res.data.page.list
          this.shopTotal = res.data.page.totalCount;
          this.$nextTick(() => {
            for (let i = 0; i < this.shopList.length; i++) {
              for (let j = 0; j < this.selShops.length; j++) {
                if (this.shopList[i].id === this.selShops[j].id) {
                  this.$refs.shopTab.toggleRowSelection(this.shopList[i], true)
                  break
                }
              }
            }
          })
        }
      })
    },
    // 获取商品列表
    getGoodsList () {
      this.shopTableLoading = true;
      serviceApione.getGoodsList(this.shopPamars).then(res => {
        this.shopTableLoading = false;
        if (res && res.data.code == 200) {
          this.shopList = res.data.page.list
          this.shopTotal = res.data.page.totalCount;
          this.$nextTick(() => {
            for (let i = 0; i < this.shopList.length; i++) {
              for (let j = 0; j < this.selShops.length; j++) {
                if (this.shopList[i].id === this.selShops[j].id) {
                  this.$refs.shopTab.toggleRowSelection(this.shopList[i], true)
                  break
                }
              }
            }
          })
        }
      })
    },
    // 开启店铺弹窗时调用
    openShopsDialog () {
      this.temShops = [];
      // this.selShops = [];
      if (this.mode === 0) {
        this.getShopList();
      } else {
        this.getGoodsList()
      }
    },
    // 关闭店铺弹窗
    closeShop () {
      this.$refs.shopTab.clearSelection();
      this.innerVisible = false;
    },
    // 选择店铺
    handleSelectionChange (e) {
      this.temShops = []
      e.forEach(v => {
        let bool = this.selShops.some(k => {
          return k.id == v.id
        })
        if (!bool) {
          this.temShops.push(v)
        }
      })
    },
    // 选择店铺 确定
    confirmShops () {
      let arr = JSON.parse(JSON.stringify(this.temShops))
      this.selShops.push(...arr);
      this.form.adapt_shop_ids = this.selShops.map(v => {
        return v.id
      })
      this.innerVisible = false
    },
    selected (row, index) {
      let bool = this.selShops.some(k => {
        return k.id == row.id
      })
      return !bool
    },
    // 删除选择的店铺
    delSelShop (row, index) {
      this.selShops.splice(index, 1)
    },
    // 获取优惠券  详情
    getDetails () {
      this.formLoading = true;
      couponApi.couponInfo(this.id).then(res => {
        if (res && res.data.code == 200) {
          this.form = res.data.data;
          // 其他活动是否参与回显处理
          this.activity_arr = [];
          this.form.adapt_activity_data.forEach((v, i) => {
            if (v.on && v.code == 'GROUPBUY') this.activity_arr.push(0)
            else if (v.on && v.code == 'SECKILL') this.activity_arr.push(1)
          })
          // 领取事件回显处理
          this.form.timeArr = [this.form.start_time, this.form.end_time]
          // 使用范围回显处理
          if (this.form.universal) this.form.modeType = 1
          else if (!this.form.adapt_or_no) this.form.modeType = 2
          else if (this.form.adapt_or_no) this.form.modeType = 3
          // 选择的店铺 回显处理
          if (this.mode === 0 && !this.form.universal && this.form.adapt_shops) {
            this.form.adapt_shops.forEach(v => {
              v.company_name = v.shop_name;
              v.province = v.address;
              v.loser = v.contact_person;
              v.mobile = v.contact_phone
            })
            this.selShops = this.form.adapt_shops
          }
          // 选择的商店 回显处理
          if (this.mode === 1 && !this.form.universal && this.form.adapt_goods) {
            this.form.adapt_goods.forEach(v => {
              v.company_name = v.shop_name;
              v.province = v.address;
              v.loser = v.contact_person;
              v.mobile = v.contact_phone
            })
            this.selShops = this.form.adapt_goods
          }
        }
        this.formLoading = false
      })
    }
  }
}
</script>
<style>
.el-form--inline .el-form-item__content {
  width: auto !important;
}
input[type='number'] {
  -moz-appearance: textfield;
}
input[type='number']::-webkit-inner-spin-button,
input[type='number']::-webkit-outer-spin-button {
  -webkit-appearance: none;
}
</style>
<style lang="scss" scoped>
.c_red {
  color: #ec0000;
}
.ml20 {
  margin-left: 20px;
}
.tableBox {
  width: 80%;
  margin-left: 150px;
}
.flex_bet {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pageBox {
  text-align: center;
  margin-top: 20px;
}
</style>